/* eslint-disable react/jsx-key */
import React, { useEffect, useRef, useState } from 'react';
import { Switch, Modal, Button, Form, Popconfirm, message, Tooltip } from 'antd';
import { connect, useRequest } from 'umi';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { getFetch, postFetch } from '@/utils/doFetch';
import { giveback } from '@/services/dossier';
import moment from 'moment';
import Uploadcom from './uploadcom';
import CompanyName from '@/components/CompanyName';


let Dossier = (props) => {
  const { global, dispatch } = props;
  let actionRef = useRef(),
    tableform = useRef(),
    ChildRef = null,
    [vs, cvs] = useState(false), //表单显/隐
    [fields, cf] = useState({}),
    [iftype, ciftype] = useState({}),
    [key, setkey] = useState('1'),
    [formRef] = Form.useForm();

  const [selectedRowKeys, setselectedRowKeys] = useState([]);

  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }

  const { run, loading } = useRequest(postFetch, {
    manual: true,
    formatResult: (res) => res,
    onSuccess: (result, params) => {
      message.destroy();
      if (result.code == 0) {
        message.success(result.message);
        actionRef.current.reload();
        cvs(false);
      } else {
        message.error(result.message);
      }
    },
  });

  const columns = [
      {
        title: '入库条码号',
        dataIndex: 'voucher_barcode',
        key: 'voucher_barcode',
      },
      {
        title: '存放位置',
        dataIndex: 'address',
        key: 'address',
        search: false,
        renderText: (text, row) => {
          return (
            <Tooltip title={text + row.rule_code} placement="topLeft">
              <span>{text + row.rule_code}</span>
            </Tooltip>
          );
        },
      },
      {
        title: '公司名称',
        width: 260,
        dataIndex: 'company_name',
        key: 'company_name',
        render: (_, row) => (
          <CompanyName
            row={{ ...row, name: row?.company_name ?? row?.name, id: row?.company_id ?? row?.id }}
            reload={reload}
          />
        ),
      },
      {
        title: '凭证月份',
        dataIndex: 'voucher_date',
        key: 'voucher_date',
        valueType: 'dateMonth',
      },
      {
        title: '入库日期',
        dataIndex: 'submit_date',
        key: 'submit_date',
        valueType: 'date',
        render: (text, row) => {
          return (
            <span>
              {row.submit_date ? moment(row.submit_date).format('YYYY/MM/DD HH:mm') : '-'}
            </span>
          );
        },
      },
      {
        title: '状态',
        dataIndex: 'process_status_name',
        key: 'process_status_name',
        search: false,
      },
      {
        title: '记账会计',
        dataIndex: 'account_name',
        key: 'account_name',
      },
      {
        title: '出借人',
        dataIndex: 'lend_user_name',
        key: 'lend_user_name',
        search: false,
      },
      {
        title: '出借拒绝人',
        dataIndex: 'lend_refuse_user_name',
        key: 'lend_refuse_user_name',
        search: false,
      },
      {
        title: '出借同意人',
        dataIndex: 'lend_agree_user_name',
        key: 'lend_agree_user_name',
        search: false,
      },
      {
        title: '出借档案管理员出库人',
        dataIndex: 'lend_out_user_name',
        key: 'lend_out_user_name',
        search: false,
      },
      {
        title: '归还人',
        dataIndex: 'give_back_pending_user_name',
        key: 'give_back_pending_user_name',
        search: false,
      },
      {
        title: '归还同意人',
        dataIndex: 'give_back_agree_user_name',
        key: 'give_back_agree_user_name',
        search: false,
      },
      {
        title: '交接人',
        dataIndex: 'hand_over_user_name',
        key: 'hand_over_user_name',
        search: false,
      },
      {
        title: '交接拒绝人',
        dataIndex: 'hand_over_refuse_user_name',
        key: 'hand_over_refuse_user_name',
        search: false,
      },
      {
        title: '交接同意人',
        dataIndex: 'handle_over_agree_user_name',
        key: 'handle_over_agree_user_name',
        search: false,
      },
      {
        title: '交接出库人',
        dataIndex: 'hand_over_out_user_name',
        key: 'hand_over_out_user_name',
        search: false,
      },
      {
        title: '接收客户',
        dataIndex: 'receive_user_name',
        key: 'receive_user_name',
        search: false,
      },
      {
        title: '出借原因',
        dataIndex: 'lend_message',
        key: 'lend_message',
        search: false,
      },
      {
        title: '出借拒绝原因',
        dataIndex: 'lend_refuse_message',
        key: 'lend_refuse_message',
        search: false,
      },
      {
        title: '交接提交原因',
        dataIndex: 'hand_over_message',
        key: 'hand_over_message',
        search: false,
      },
      {
        title: '交接拒绝信息',
        dataIndex: 'hand_over_refuse_message',
        key: 'hand_over_refuse_message',
        search: false,
      },
      {
        title: '操作',
        valueType: 'option',
        width: 92,
        render: (text, row, _, action) => extraAction(text, row, _, action),
      },
    ],
    columnes = [
      {
        title: '凭证入库条码号',
        dataIndex: 'voucher_barcode',
        key: 'voucher_barcode',
      },
      {
        title: '公司名称',
        width: 260,
        dataIndex: 'company_name',
        key: 'company_name',
        render: (_, row) => (
          <CompanyName
            row={{ ...row, name: row?.company_name ?? row?.name, id: row?.company_id ?? row?.id }}
            reload={reload}
          />
        ),
      },
      {
        title: '凭证月份',
        dataIndex: 'voucher_date',
        key: 'voucher_date',
        valueType: 'dateMonth',
      },
      {
        title: '入库日期',
        dataIndex: 'submit_date',
        key: 'submit_date',
        valueType: 'date',
        render: (text, row) => {
          return (
            <span>
              {row.submit_date ? moment(row.submit_date).format('YYYY-MM-DD HH:mm:ss') : '-'}
            </span>
          );
        },
      },
      {
        title: '出借原因',
        dataIndex: 'lend_message',
        key: 'lend_message',
        search: false,
      },
      {
        title: '出借拒绝原因',
        dataIndex: 'lend_refuse_message',
        key: 'lend_refuse_message',
        search: false,
      },
      {
        title: '交接提交原因',
        dataIndex: 'hand_over_message',
        key: 'hand_over_message',
        search: false,
      },
      {
        title: '交接拒绝信息',
        dataIndex: 'hand_over_refuse_message',
        key: 'hand_over_refuse_message',
        search: false,
      },
      {
        title: '状态',
        dataIndex: 'process_status_name',
        key: 'process_status_name',
        search: false,
      },

      {
        title: '操作',
        valueType: 'option',
        width: 160,
        render: (text, row, _, action) => extraActions(text, row, _, action),
      },
    ];

  function extraAction(text, record, _, action) {
    return [
      <a
        disabled={record.process_status != 'in_store'}
        onClick={() => {
          if (record.process_status != 'in_store') {
            return;
          }
          ciftype({
            val: 'bro',
            id: [record.id],
            title: '出借',
          });
          cf(() => {
            return {
              message: {
                value: null,
                type: 'textarea',
                title: '申请原因',
                name: ['message'],
                required: false,
                col: { span: 24 },
              },
            };
          });
          cvs(true);
        }}
      >
        出借
      </a>,
      <a
        disabled={record.process_status != 'in_store'}
        style={{ color: record.process_status != 'in_store' ? 'rgba(0, 0, 0, 0.25)' : 'red' }}
        onClick={() => {
          if (record.process_status != 'in_store') {
            return;
          }
          ciftype({
            val: 'exc',
            id: [record.id],
            title: '交接',
          });
          cf(() => {
            return {
              message: {
                value: null,
                type: 'textarea',
                title: '交接备注',
                name: ['message'],
                required: false,
                col: { span: 24 },
              },
            };
          });
          cvs(true);
        }}
      >
        交接
      </a>,
      // <Popconfirm
      //     title="确认删除该子账号？"
      //     onConfirm={() => {
      //         run({ url: "/ngic-promote-epauth/epUser/deleteSon", params: { id: record.id } });
      //     }}
      // >
      //     <a style={{ color: "red" }}>删除</a>
      // </Popconfirm>
    ];
  }

  function extraActions(text, record, _, action) {
    return [
      <Popconfirm
        title="确认归还该凭证？"
        onConfirm={() => {
          giveback({ id: record.id }).then((res) => {
            if (res.code == 0) {
              message.success('操作成功');
              reload();
            }
          });
        }}
        disabled={record.process_status != 'lend_out_store'}
      >
        <a disabled={record.process_status != 'lend_out_store'}>归还</a>
      </Popconfirm>,
      // <Popconfirm
      //     title="确认交接该凭证给客户？"
      //     onConfirm={() => {
      //         handoveroutstore({ id: record.id }).then(res => {
      //             if (res.code == 0) {
      //                 message.success("操作成功");
      //                 reload();
      //             }
      //         })
      //     }}
      //     disabled={record.process_status != "confirm_pending"}
      // >
      //     <a disabled={record.process_status != "confirm_pending"}>
      //         确认交接
      //     </a>
      // </Popconfirm>
    ];
  }

  let saveData = (values, fn) => {
    //  /wbn-api/voucher/lend_company
    if (iftype.val == 'bro') {
      dispatch({
        type: 'dossier/lendcompany',
        payload: { ...values, ids: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
          setselectedRowKeys([]);
        }
      });
    } else if (iftype.val == 'exc') {
      dispatch({
        type: 'dossier/handover',
        payload: { ...values, ids: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
          setselectedRowKeys([]);
        }
      });
    }
  };

  return (
    <div className="nopa autotable">
      <AutoTable
        formRef={tableform}
        tabList={[
          {
            key: '1',
            tab: '全部凭证',
          },
          {
            key: '0',
            tab: '我的凭证',
          },
        ]}
        onTabChange={(val) => {
          setkey(val);
        }}
        pagetitle={props.route.name}
        pageextra={[
          <a
            rel="noreferrer"
            onClick={() => {
              let token = localStorage.getItem('TOKEN');
              fetch('/wbn-api/voucher/download_import_template', {
                headers: {
                  'Content-Type': 'application/json',
                  Accept: 'application/json',
                  Authorization: token,
                },
              })
                .then((response) => response.blob())
                .then((blob) => {
                  // 创建一个 Blob 对象
                  const blobObject = new Blob([blob]);

                  // 创建一个下载链接
                  const downloadLink = document.createElement('a');
                  const objectURL = URL.createObjectURL(blobObject);

                  // 设置链接属性
                  downloadLink.href = objectURL;
                  downloadLink.download = '凭证导入模板.xlsx'; // 例如：'downloaded_file.txt'

                  // 模拟点击下载链接
                  document.body.appendChild(downloadLink);
                  downloadLink.click();

                  // 移除链接元素
                  document.body.removeChild(downloadLink);

                  // 释放对象 URL
                  URL.revokeObjectURL(objectURL);
                })
                .catch((error) => console.error('下载失败:', error));
            }}
          >
            下载凭证模板
          </a>,
          <a
            style={{ margin: '0 12px' }}
            onClick={() => {
              cvs(true);
              ciftype({
                val: 'inside',
                title: '凭证导入',
              });
            }}
          >
            凭证导入
          </a>,
          <a
            onClick={() => {
              const hide = message.loading('正在导出..', 0);
              let params = tableform.current.getFieldsValue();
              params.voucher_date = params.voucher_date
                ? moment(params.voucher_date).format('YYYY-MM')
                : null;
              params = {
                ...params,
                is_all: key,
              };
              getFetch({ url: '/wbn-api/voucher/download_voucher_manage', params }).then((res) => {
                window.open(res?.data);
                hide();
              });
            }}
          >
            导出
          </a>,
        ]}
        columns={key == '1' ? columns : columnes}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        extraparams={{ is_all: key }}
        path="/wbn-api/voucher/voucher_manage"
        rowSelection={{
          selectedRowKeys: selectedRowKeys,
          preserveSelectedRowKeys: true,
          onChange: (selectedRowKeyes, selectedRows) => {
            setselectedRowKeys(selectedRowKeyes);
          },
          getCheckboxProps: (record) => ({
            disabled: record.process_status != 'in_store', // Column configuration not to be checked
          }),
        }}
        tabBarExtraContent={
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <a
              disabled={selectedRowKeys.length == 0}
              style={{ marginRight: 12 }}
              onClick={() => {
                if (selectedRowKeys.length == 0) {
                  return;
                }
                ciftype({
                  val: 'bro',
                  id: selectedRowKeys,
                  title: '出借',
                });
                cf(() => {
                  return {
                    message: {
                      value: null,
                      type: 'textarea',
                      title: '申请原因',
                      name: ['message'],
                      required: false,
                      col: { span: 24 },
                    },
                  };
                });
                cvs(true);
              }}
            >
              出借
            </a>
            <a
              disabled={selectedRowKeys.length == 0}
              style={{ color: selectedRowKeys.length == 0 ? 'rgba(0, 0, 0, 0.25)' : 'red' }}
              onClick={() => {
                if (selectedRowKeys.length == 0) {
                  return;
                }
                ciftype({
                  val: 'exc',
                  id: selectedRowKeys,
                  title: '交接',
                });
                cf(() => {
                  return {
                    message: {
                      value: null,
                      type: 'textarea',
                      title: '交接备注',
                      name: ['message'],
                      required: false,
                      col: { span: 24 },
                    },
                  };
                });
                cvs(true);
              }}
            >
              交接
            </a>
          </div>
        }
      />

      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        destroyOnClose={true}
      >
        {iftype.val == 'inside' ? (
          <div>
            <Uploadcom
              reload={() => {
                reload();
                cvs(false);
              }}
            />
          </div>
        ) : (
          <InitForm
            formRef={formRef}
            fields={fields}
            submitData={(values, fn) => {
              saveData(values, fn);
            }}
            onChange={(changedValues, allValues) => {}}
            submitting={loading || !vs}
            halfsave={false}
          />
        )}
      </Modal>
    </div>
  );
};

export default connect(({ global, loading }) => ({
  global,
  loading,
}))(Dossier);
